import { Injectable } from '@nestjs/common';
import { DbService } from 'apps/admin/src/db/db.service';
import CreateDto from './dto/create.dto';
import UpdateDto from './dto/update.dto';
import { RechargeOption } from '@app/db/entity/RechargeOption';

@Injectable()
export class OptionService {
    constructor(
        private readonly db:DbService
    ) {}

    list() {
        return this.db.rechargeOption.find(null, null, null, null, {id : 'DESC'})
    }


    async add(dto:CreateDto) {
        return this.db.rechargeOption.insert(dto)
    }

    async update(dto:UpdateDto) {
        const id = dto.id
        const row = await this.db.rechargeOption.findOne({id : id}, {enable : true, amount : true, reward : true})
        if(!row) return false

        const updateData:KeyToValueType<RechargeOption> = {}

        for(let k in row) {
            if(k in dto) {
                if(dto[k] != row[k]) {
                    updateData[k] = dto[k]
                }
            }
        }

        return this.db.rechargeOption.update({id}, updateData)
    }

    async del(id:number) {
        let row = await this.db.rechargeOption.findOne({ id }, ['id'])
        if(!row) return false
        return this.db.rechargeOption.delete({id : id})
    }

}
